const express = require('express');
const pool = require('../pool.js');
const r = express.Router();
//注册用户接口
// post  /user/reg
// 

r.post('/reg', (req, res, next) => {
  var obj = req.body;
  console.log(obj);
  pool.query('insert into  user set ?', [obj], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    res.send({
      "code": 1,
      "msg": "注册成功",
      "data": result         //这里是个对象
    });
  });

});
// 用户登录接口
// post /user/login
r.post('/login', (req, res, next) => {
  var obj = req.body;
  console.log(obj);
  pool.query('select * from  user  where phone=? && upwd=?',
    [obj.phone, obj.upwd],
    (err, result) => {
      if (err) {
        next(err);
        return;
      }
      if (result.length == 0) {
        res.send({
          "code": 0,
          "msg": "找不到用户登陆失败"
        });
      } else {
        res.send({
          "code": 1,
          "msg": "登陆成功",
          "data": result           //这里是个数组
        });
      }

    });

});

// 用户查询接口  get /list query传参
r.get('/list', (req, res, next) => {
  var obj = req.query;
  console.log(obj);
  pool.query('select * from user where phone=?', [obj.phone], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    if (result.length == 0) {
      res.send({
        "code": 0,
        "msg": "查询失败"
      });
    } else {
      res.send({
        "code": 1,
        "msg": "查询成功",
        "data": result         //查询出是数组数据
      });
    }
  });

});

// 删除用户接口   delete 路由传参
r.delete('/del/:uid', (req, res, next) => {
  console.log(req.params);
  pool.query('delete  from user where uid=?', [req.params.uid], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    console.log(result);
    if (result.affectedRows == 0) {
      res.send({
        code: 0,
        msg: "删除失败"

      });
    } else {
      res.send({
        code: 1,
        msg: "删除成功"
      });
    }
  });

});


module.exports = r;